package top.lshaci.learning.springboot.security.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import top.lshaci.learning.springboot.security.entity.Permission;
import top.lshaci.learning.springboot.security.entity.Users;
import top.lshaci.learning.springboot.security.mapper.PermissionMapper;
import top.lshaci.learning.springboot.security.mapper.UsersMapper;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * UserDetailsServiceImpl
 *
 * @author lshaci
 * @since 1.0.0
 */
@Service
@AllArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UsersMapper usersMapper;

    private final PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<Users> query = Wrappers.lambdaQuery(Users.class).eq(Users::getUsername, username);
        Users users = usersMapper.selectOne(query);
        if (Objects.isNull(users)) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        List<Permission> permissions = permissionMapper.selectByUserId(users.getId());
        List<SimpleGrantedAuthority> authorities = permissions.stream()
                .map(p -> new SimpleGrantedAuthority(p.getName()))
                .collect(Collectors.toList());

        return User
                .withUsername(users.getUsername())
                .password(users.getPassword())
                .authorities(authorities)
                .build();
    }
}
